package com.shioirikukuri.controller;

import com.shioirikukuri.common.until.PictureUtil;
import com.shioirikukuri.entity.Food;
import com.shioirikukuri.service.IFoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/foods")
public class FoodController {

	@Autowired
	private IFoodService foodService;

	/**
	 * 获取所有食物信息
	 * @return
	 */
	@GetMapping
	public ResponseEntity<List<Food>> getAllFoods() {
		List<Food> foods = foodService.getAllFoods();
		return ResponseEntity.ok(foods);
	}

	/**
	 * 获取指定ID的食物信息
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	public ResponseEntity<?> getFoodById(@PathVariable Long id) {
		Optional<Food> food = foodService.getFoodById(id);
		if (food.isPresent()) {
			return ResponseEntity.ok(food.get());
		} else {
			return ResponseEntity.notFound().build();
		}
	}

	/**
	 * 获取指定类别ID的食物信息
	 * @param categoryId
	 * @return
	 */
	 @GetMapping("/category/{categoryId}")
	 public ResponseEntity<List<Food>> getFoodsByCategoryId(@PathVariable Long categoryId) {
		List<Food> foods = foodService.getFoodsByCategoryId(categoryId);
		return ResponseEntity.ok(foods);
	 }

	/**
	 * 添加食物信息
	 * @param food
	 * @return
	 */
	@PostMapping
	public ResponseEntity<Food> addFood(@RequestBody Food food) {
		Food createdFood = foodService.addFood(food);
		return ResponseEntity.status(201).body(createdFood);
	}

	@PutMapping("/{id}")
	public ResponseEntity<?> updateFood(@PathVariable Long id, @RequestBody Food food) {
		try {
			Food updatedFood = foodService.updateFood(id, food);
			return ResponseEntity.ok(updatedFood);
		} catch (Exception e) {
			return ResponseEntity.notFound().build();
		}
	}

	@DeleteMapping("/{id}")
	public ResponseEntity<Void> deleteFood(@PathVariable Long id) {
		foodService.deleteFood(id);
		return ResponseEntity.noContent().build();
	}






	private String getExtension(String filename) {
		if (filename == null) {
			return "";
		}
		int lastUnixPos = filename.lastIndexOf('/');
		int lastWindowsPos = filename.lastIndexOf('\\');
		int index = Math.max(lastUnixPos, lastWindowsPos);
		return filename.substring(index + 1).contains(".") ? filename.substring(filename.lastIndexOf('.') + 1) : "";
	}
}